package cn.pugle.ormtest.ebean.domain.finder;

import cn.pugle.ormtest.ebean.domain.CustomerModel2;
import cn.pugle.ormtest.ebean.domain.dto.CustomerDetail;
import cn.pugle.ormtest.ebean.domain.query.QCustomerModel2;
import io.ebean.Finder;
import io.ebean.RawSql;
import io.ebean.RawSqlBuilder;

import java.util.List;

/**
 * @author tzp
 * @date 2017/12/27
 */
public class CustomerFinder extends Finder<Long, CustomerModel2> {


    public CustomerFinder() {
        super(CustomerModel2.class);
    }

    public CustomerFinder(String serverName) {
        super(CustomerModel2.class, serverName);
    }

    /**
     * 返回query bean
     */
    public QCustomerModel2 where() {
        return new QCustomerModel2(db());
    }

    public List<CustomerDetail> customerDetail() {
        String sql = "select c.id, c.name, count(o.id) as order_count " +
                " from st_customer2 c left join st_order2 o on o.customer_id = c.id " +
                " group by c.id";
        RawSql rawSql = RawSqlBuilder.parse(sql)
                .columnMapping("c.id", "customer.id")
                .columnMapping("c.name", "customer.name")
                .columnMapping("order_count", "orderCount")
                .create();
        List<CustomerDetail> list = db().find(CustomerDetail.class)
                .setRawSql(rawSql)
                .where().ge("c.id", 1L)
                .findList();
        return list;
    }
}
